#! /usr/bin/env python
# -*- coding: utf-8 -*-
import json
import datetime

from flask import request
from flask import Blueprint
from flask_login import login_required

from app import db, app
from app import global_params
from app.models import Loan

bp = Blueprint("loans", __name__, template_folder="template",
               static_folder="static")


@bp.route("/change", methods=["POST"])
@login_required
def loans_change():
    lid = request.form.get('pk')  # username
    value = request.form.get('value')
    name = request.form.get('name')

    if name not in ("status", "comment", "end", "channel", "repayment"):
        return "update error", 500

    try:
        loan = Loan.query.filter_by(id=lid).first()
        loan.change(name, value)
        db.session.add(loan)
        db.session.commit()
        return "ok", 200

    except Exception as e:
        app.logger.error("change loan %s failed. %s " % (name, str(e)))
        db.session.rollback()
        return "update err", 500


@bp.route("/update/<operation>", methods=["POST"])
@login_required
def loans_update_operation(operation):
    lid = request.form.get("lid", type=int)

    if operation not in ("ok", "pending", "delay", "delay_ok"):
        return json.dumps({"status": 500, "message": u"错误操作!"})

    try:
        loan = Loan.query.filter_by(id=lid).first()

        if operation == "ok":
            app.logger.info("change loan %(lid)s ok" % {"lid": lid})
            loan.end_loan()
            db.session.add(loan)
        elif operation == "delay":
            app.logger.info("change loan %(lid)s delay" % {"lid": lid})
            loan.delay_loan()
            db.session.add(loan)
        elif operation == "delay_ok":
            app.logger.info("change loan %(lid)s delay_ok" % {"lid": lid})
            loan.delay_loan_ok()
            db.session.add(loan)

        # todo pending need rewrite
        elif operation == "pending":
            app.logger.info("change loan %(lid)s pending" % {"lid": lid})
            new_loan = _create_new_loan(loan)
            loan.pending_loan()
            db.session.add(new_loan)
            db.session.add(loan)
        db.session.commit()

    except Exception as e:
        app.logger.exception(str(e))
        db.session.rollback()
        return json.dumps({"status": 500, "message": u"修改借款状态失败!"})
    else:
        return json.dumps({"status": 200, "message": u"修改借款信息成功!"})


@bp.route("/change/comment", methods=["POST"])
@login_required
def change_comment():
    l_id = request.form.get("lid", type=int)
    comment = request.form.get("comment")
    try:
        loan = Loan.query.filter_by(id=l_id).first()
        loan.comment = comment
        db.session.add(loan)
        db.session.commit()
    except Exception as e:
        app.logger.exception(str(e))
        return json.dumps({"status": 500, "message": u"更新评论失败"})
    else:
        return json.dumps({"status": 200, "message": u"更新评论成功"})


def _create_new_loan(loan):

    now = datetime.datetime.now()
    money = loan.money
    commission = loan.commission
    iphone = loan.iphone
    status = 2
    end = 0
    entry = loan.entry
    create_time = now,
    channel = loan.channel
    comment = loan.comment
    client_id = loan.client_id
    start_time = loan.end_time
    end_time = start_time + datetime.timedelta(
        days=global_params.PENDING_DELTA_DAYS)

    new_loan = Loan(
        money=money, commission=commission, iphone=iphone,
        status=status, end=end, entry=entry,
        create_time=create_time, channel=channel,
        comment=comment, client_id=client_id,
        start_time=start_time, end_time=end_time
    )

    return new_loan
